//
//  EDJHttpOperation.m
//  EDJCoreFramework
//
//  Created by 王芳 on 16/4/22.
//  Copyright © 2016年 edaijia-inc. All rights reserved.
//

#import "EDJHttpOperation.h"
#import "EDJHttpClient.h"

@interface EDJHttpOperation ()
@property (nonatomic,strong,readwrite) NSURLSessionTask *task;
@end

@implementation EDJHttpOperation

- (instancetype)initWithRequest:(NSURLRequest *)request manager:(AFHTTPSessionManager *)manager success:(void(^)(NSURLSessionDataTask * task,id value))success failure:(void(^)(NSURLSessionDataTask *task, NSError *error))failure{
    EDJHttpOperation *operation = [[EDJHttpOperation alloc] init];
    __block NSURLSessionDataTask *dataTask = nil;
    __weak typeof(self) weakOperation = operation;
    dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        if (error) {
            NSLog(@"error %@",error);
            if (failure) {
                failure(dataTask,error);
            }
        }else{
            if (success) {
                success(dataTask,responseObject);
            }
        }
        [weakOperation completeOperation];
    }];
    operation.task = dataTask;
    return operation;
}

- (void)main{
    [self.task resume];
}

- (void)completeOperation{
    [super completeOperation];
    self.task = nil;
}

- (void)start{
    [[EDJHttpClient instance].operationQueue addOperation:self];
}

@end
